import { ipcMain } from "electron-better-ipc"
import { IWorkSpaceHistoryItem } from "./interfaces"
import { WORK_SPACE_HISTORY_FILE } from "./paths"
import { readJson, writeJson } from "./utils"
import * as fs from 'node:fs'

// 读取历史记录数据
export const readWorkSpaceHistory = () => {
    // 历史打开的工作空间列表
    if (!fs.existsSync(WORK_SPACE_HISTORY_FILE)) {
        writeJson(WORK_SPACE_HISTORY_FILE, [])
    }
    return readJson(WORK_SPACE_HISTORY_FILE) as IWorkSpaceHistoryItem[]
}

// 更新最后访问事件
export const updateWorkSpaceAccessTime = (id: string) => {
    const workSpaceHistory = readWorkSpaceHistory()
    const index = workSpaceHistory.findIndex(item => item.id === id)
    if (index !== -1) {
        // 更新时间
        workSpaceHistory[index].lastAccessTime = Date.now()
        // 放在顶部
        workSpaceHistory.unshift(workSpaceHistory.splice(index, 1)[0])
    }
    saveWorkSpaceHistory(workSpaceHistory)
}

// 保存
export const saveWorkSpaceHistory = (data: IWorkSpaceHistoryItem[]) => {
    writeJson(WORK_SPACE_HISTORY_FILE, data)
}

ipcMain.answerRenderer('readWorkSpaceHistory', readWorkSpaceHistory)
ipcMain.answerRenderer('updateWorkSpaceAccessTime', updateWorkSpaceAccessTime)
ipcMain.answerRenderer('saveWorkSpaceHistory', saveWorkSpaceHistory)